package com.example.musicserver.controller;

import com.example.musicserver.config.ResponseBodyMessage;
import com.example.musicserver.constant.Constants;

import com.example.musicserver.model.Music;
import com.example.musicserver.service.LoveMusicService;
import com.example.musicserver.service.MusicService;
import com.example.musicserver.tools.FileVerify;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-01-17
 * Time: 14:20
 */
@Slf4j
@RestController
@RequestMapping("/music")
public class MusicController {
    @Autowired
    private MusicService musicService;
    @Autowired
    private LoveMusicService loveMusicService;

    @Value("${music.local.path}")
    private String SAVE_PATH ;//使用反斜杠，用英文路径，部署在Linux上，避免不能识别

    /**
     * 上传音乐
     * @param singer
     * @param file
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/upload")
    public ResponseBodyMessage<Boolean> insertMusic(@RequestParam String singer
            , @RequestParam("fileName")MultipartFile file , HttpServletRequest request
            , HttpServletResponse response) throws IOException {
        //1:检查是否登录了
        HttpSession httpSession = request.getSession(false);//当前没有会话不创建会话，默认为true
        if(httpSession == null ||
                httpSession.getAttribute(Constants.USERINFO_SESSION_KEY) == null){
            return new ResponseBodyMessage<>(-1,"没有登陆",false);
        }

        //2:检验是否是mp3文件格式
        Boolean result = FileVerify.isMP3File(file);
        if(result == false){
            return new ResponseBodyMessage<>(-1,"上传的文件格式错误",false);
        }


        String fileNameAndType = file.getOriginalFilename();//获取文件的完整名称，包括文件名称和文件拓展名,xxx.mp3
        System.out.println("fileNameAndType----->" + fileNameAndType);
        String path = SAVE_PATH + "/" + fileNameAndType;//文件的存储路径
        File dest = new File(path);//用这个存储路径new 一个file ， dest现在就相当于 前端传进来的file可以这么理解

        //3：music上传到服务器
        Boolean result2 = musicService.uploadServer(file, path);
        if(!result2){
            return new ResponseBodyMessage<>(-1,"服务器上传失败",false);
        }

        //4:进行数据库的上传
        // （1）准备数据 （2）调用insert
        int ret = musicService.uploadDatebase(fileNameAndType,httpSession,singer);
        if(ret == 1){
            response.sendRedirect("/list.html");//前端实现完毕，上传成功进行跳转页面(重定向)
        } else if (ret == -1) {//已经存在该音乐了
            return new ResponseBodyMessage<>(-1,"数据库中已经存在该音乐",false);
        } else {
            dest.delete();//上传数据库失败
            return new ResponseBodyMessage<>(-1,"数据库上传失败",false);
        }
        return new ResponseBodyMessage<>(0,"数据库上传成功",true);
    }

    /**
     * 播放音乐的时候 ：/music/get?path=xxx.mp3
     * @param path
     * @return
     */
    @RequestMapping("/getMusic")
    public ResponseEntity<byte[]> getMusic(String path){
        File file = new File(SAVE_PATH + "/" + path);
        byte[] a = null;
        try {
            a = Files.readAllBytes(file.toPath());
            if(a == null){
                return ResponseEntity.badRequest().build();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok(a);
    }

    /**
     * 删除单首音乐
     * @param id
     * @return
     */
    @RequestMapping("/deleteMusic")
    public ResponseBodyMessage<Boolean> deleteMusic(@RequestParam String id){
        int iid = Integer.parseInt(id);
        Music music = musicService.findMusicById(iid);
        if(music == null){
            return new ResponseBodyMessage<>(-1,"没有找到你要删除的音乐",false);
        }

        int result = musicService.deleteMusic(iid,music);
        if(result == -1){
            return new ResponseBodyMessage<>(-1,"删除数据库中的音乐失败",false);
        }else if(result == -2){
            return new ResponseBodyMessage<>(-1,"删除服务器中的音乐失败",false);
        }
        //库中和服务器中都删除成功，现在看收藏中是否含有该音乐，若有则删
        int ret = loveMusicService.deleteLoveMusicById(iid);
        if(ret == 1){
            log.info("收藏中该音乐也被删除");
        }
        return new ResponseBodyMessage<>(0,"删除服务器中的音乐成功",true);
    }

    /**
     * 批量删除音乐
     * @param idList
     * @return
     */
    @RequestMapping("/batchDeleteMusic")
    public ResponseBodyMessage<Boolean> batchDeleteMusic(@RequestParam("id") List<Integer> idList){
        int sum = 0;
        for(int i = 0 ; i < idList.size() ; i++){
            int id = idList.get(i);
            Music music = musicService.findMusicById(id);
            int result = musicService.deleteMusic(id, music);
            if(result == -1){
                return new ResponseBodyMessage<>(-1,"删除数据库中的音乐失败",false);
            }else if(result == -2){
                return new ResponseBodyMessage<>(-1,"删除服务器中的音乐失败",false);
            }
            loveMusicService.deleteLoveMusicById(music.getId());
            sum += result;
        }
        if(sum == idList.size()){
            return new ResponseBodyMessage<>(0,"批量删除成功",true);
        }else{
            return new ResponseBodyMessage<>(-1,"批量删除失败",false);
        }
    }

    /**
     * 找歌曲
     * @param musicName 可以传入参数
     * @return
     */
    @RequestMapping("/findMusic")
    public ResponseBodyMessage<List<Music>> findMusic(@RequestParam(required = false) String musicName){
        log.info("查询界面");
        List<Music> musicList = null;
        if(musicName == null){
            musicList = musicService.findAllMusic();
        }else {
            musicList = musicService.findMusic(musicName);
        }
        return new ResponseBodyMessage<>(0,"查询到了歌曲信息",musicList);
    }



}
